package com.clb.toolsbox.toolsJPanel;

import com.intellij.ui.JBColor;
import com.intellij.ui.components.JBScrollPane;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JsonFormatTool extends JPanel {

    private JTextArea inputArea;
    private JTextArea outputArea;
    private JButton formatButton;
    private JButton copyButton;
    // 新增字段：记录是否已经输入内容或是否显示了占位符
    private boolean placeholderVisible = true;

    public JsonFormatTool() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 输入区域
        inputArea = new JTextArea();
        inputArea.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14));
        inputArea.setLineWrap(true);
        inputArea.setWrapStyleWord(true);
        JScrollPane inputScroll = new JBScrollPane(inputArea);
        // 设置默认的提示文本
        setPlaceholder(inputArea, "请输入 JSON 内容...");
        // 添加焦点监听器
        inputArea.addFocusListener(new java.awt.event.FocusAdapter() {
            @Override
            public void focusGained(java.awt.event.FocusEvent e) {
                if (placeholderVisible) {
                    inputArea.setText(""); // 清除占位符
                    placeholderVisible = false;
                }
            }

            @Override
            public void focusLost(java.awt.event.FocusEvent e) {
                if (inputArea.getText().trim().isEmpty()) {
                    setPlaceholder(inputArea, "请输入 JSON 内容..."); // 重新设置占位符
                }
            }
        });

        // 输出区域
        outputArea = new JTextArea();
        outputArea.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 14));
        outputArea.setEditable(false);
        outputArea.setLineWrap(true);
        outputArea.setWrapStyleWord(true);
        JScrollPane outputScroll = new JBScrollPane(outputArea);

        // 按钮
        formatButton = new JButton("格式化");
        formatButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                formatJson();
            }
        });

        // 按钮：复制
        copyButton = new JButton("复制");
        copyButton.addActionListener(e -> {
            String text = outputArea.getText();
            if (text != null && !text.isEmpty()) {
                Toolkit.getDefaultToolkit()
                        .getSystemClipboard()
                        .setContents(new StringSelection(text), null);
                JOptionPane.showMessageDialog(JsonFormatTool.this, "内容已复制到剪贴板");
            } else {
                JOptionPane.showMessageDialog(JsonFormatTool.this, "输出区域为空，无法复制", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        // 布局
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, inputScroll, outputScroll);
        splitPane.setDividerLocation(200);
        splitPane.setResizeWeight(0.5);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(formatButton);
        buttonPanel.add(copyButton); // 添加复制按钮

        add(splitPane, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
    }

    private void formatJson() {
        String input = inputArea.getText();
        try {
            // 简单的格式美化（实际可替换为 Gson 或 Jackson）
            String formatted = formatJsonSimple(input);
            outputArea.setText(formatted);
        } catch (Exception ex) {
            outputArea.setText("格式错误: " + ex.getMessage());
        }
    }

    /**
     * 设置带有占位符效果的文本框
     */
    private void setPlaceholder(JTextArea textArea, String placeholderText) {
        textArea.setText(placeholderText);
        textArea.setForeground(JBColor.GRAY); // 设置灰色文字表示提示
        placeholderVisible = true;
    }

    // 简易格式化方法（演示用，实际建议使用库）
    private String formatJsonSimple(String json) {
        StringBuilder sb = new StringBuilder();
        int indent = 0;
        boolean inString = false;
        char[] chars = json.toCharArray();

        for (char c : chars) {
            if (c == '"' && (sb.length() == 0 || sb.charAt(sb.length() - 1) != '\\')) {
                inString = !inString;
            }

            if (!inString) {
                if (c == '{' || c == '[') {
                    sb.append(c).append("\n");
                    indent += 4;
                    appendIndent(sb, indent);
                } else if (c == '}' || c == ']') {
                    indent -= 4;
                    sb.append("\n");
                    appendIndent(sb, indent).append(c);
                } else if (c == ',') {
                    sb.append(c).append("\n");
                    appendIndent(sb, indent);
                } else {
                    sb.append(c);
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    private StringBuilder appendIndent(StringBuilder sb, int indent) {
        for (int i = 0; i < indent; i++) {
            sb.append(' ');
        }
        return sb;
    }
}
